package com.meepo.framework.design.upgrade;

import android.app.Activity;
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.meepo.framework.design.upgrade.listener.IUpgradeListener;
import com.meepo.framework.design.upgrade.listener.impl.DefaultUpgradeListener;
import com.meepo.framework.design.upgrade.listener.impl.SilenceUpgradeListener;
import com.meepo.framework.design.upgrade.service.DownloadService;
import com.meepo.framework.design.upgrade.utils.UpgradeUtils;

import java.io.File;
import java.io.Serializable;

/**
 * 版本更新管理器
 */
public class AppUpgrader implements Serializable {
    final static String INTENT_KEY = "update_dialog_values";
    final static String THEME_KEY = "theme_color";
    final static String TOP_IMAGE_KEY = "top_resId";


    private final Activity activity;

    private final int themeColor;

    private final boolean update;
    //新版本号
    private final String newVersion;
    //新app下载地址
    private final String apkFileUrl;
    //更新日志
    private final String upgradeLog;
    //配置默认更新dialog 的title
    private final String title;
    //新app大小
    private final String targetSize;
    //是否强制更新
    private final boolean constraint;
    private final String apkFileMd5;

    private final String targetPath;
    private final boolean hideDialog;
    private final boolean ignorable;
    private final boolean dismissProgress;
    private final boolean onlyWifi;

    private IUpgradeListener upgradeListener;

    public boolean isDismissProgress() {
        return dismissProgress;
    }

    public String getNewVersion() {
        return newVersion;
    }

    public String getApkFileUrl() {
        return apkFileUrl;
    }

    public String getTargetPath() {
        return targetPath;
    }

    public String getApkFileMd5() {
        return apkFileMd5;
    }

    public Activity getActivity() {
        return activity;
    }

    public int getThemeColor() {
        return themeColor;
    }

    public boolean isUpdate() {
        return update;
    }

    public String getUpgradeLog() {
        return upgradeLog;
    }

    public String getTitle() {
        return title;
    }

    public String getTargetSize() {
        return targetSize;
    }

    public boolean isConstraint() {
        return constraint;
    }

    public boolean isHideDialog() {
        return hideDialog;
    }

    public boolean isIgnorable() {
        return ignorable;
    }

    public boolean isOnlyWifi() {
        return onlyWifi;
    }


    private AppUpgrader(Builder builder) {

        activity = builder.activity;
        themeColor = builder.themeColor;
        update = builder.update;
        newVersion = builder.newVersion;
        apkFileUrl = builder.apkFileUrl;
        upgradeLog = builder.upgradeLog;
        title = builder.title;
        targetSize = builder.targetSize;
        constraint = builder.constraint;
        apkFileMd5 = builder.apkFileMd5;
        targetPath = builder.targetPath;
        hideDialog = builder.hideDialog;
        ignorable = builder.ignorable;
        dismissProgress = builder.dismissProgress;
        onlyWifi = builder.onlyWifi;
        upgradeListener = builder.upgradeListener;

    }

    private boolean ignore() {
        //版本忽略
        if (ignorable && UpgradeUtils.isNeedIgnore(activity, newVersion)) {
            return true;
        }

        return false;
    }

    /**
     * 跳转到更新页面
     */
    public void showDialogFragment() {

        if (ignore()) return;
        if (activity.isFinishing()) return;
        if (onlyWifi && !UpgradeUtils.isWifi(activity)) return;

        Bundle bundle = new Bundle();
        //添加信息，
        bundle.putSerializable(INTENT_KEY, this);

        UpgradeDialog
                .newInstance(bundle)
                .setUpgradeListener(upgradeListener)
                .show(((FragmentActivity) activity).getSupportFragmentManager(), "dialog");

    }

    public void upgrade() {
        upgrade(false);
    }

    public void upgrade(boolean silenced) {

        if (!update) {
            upgradeListener.onNoNewVersion(this);
            return;
        }

        if (upgradeListener == null) {
            if (silenced) upgradeListener = new SilenceUpgradeListener();
            else upgradeListener = new DefaultUpgradeListener();
        }

        upgradeListener.onBefore(this);

        if (DownloadService.isRunning || UpgradeDialog.isShowing) {
            Toast.makeText(activity, "app正在更新", Toast.LENGTH_SHORT).show();
        }

        upgradeListener.onShowDialog(this);
    }


    public void download(@Nullable final DownloadService.DownloadCallback downloadCallback) {

        final AppUpgrader appUpgrader = this;
//        mUpdateApp.setHttpManager(mHttpManager);
        DownloadService.bindService(activity.getApplicationContext(), new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                ((DownloadService.DownloadBinder) service).start(appUpgrader, downloadCallback);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        });
    }

    /**
     * 后台下载
     */
    public void download() {
        download(null);
    }

    public static class Builder {


        public Builder(@NonNull Activity activity) {
            this.activity = activity;
        }


        private final Activity activity;

        private int themeColor;

        private boolean update;
        //新版本号
        private String newVersion;
        //新app下载地址
        private String apkFileUrl;
        //更新日志
        private String upgradeLog;
        //配置默认更新dialog 的title
        private String title;
        //新app大小
        private String targetSize;
        //是否强制更新
        private boolean constraint;
        private String apkFileMd5;


        private String targetPath;
        private boolean hideDialog;
        private boolean ignorable;
        private boolean dismissProgress;
        private boolean onlyWifi;

        private IUpgradeListener upgradeListener;


        public Builder setThemeColor(int themeColor) {
            this.themeColor = themeColor;
            return this;
        }

        public Builder setUpdate(boolean update) {
            this.update = update;
            return this;

        }

        public Builder setNewVersion(String newVersion) {
            this.newVersion = newVersion;
            return this;

        }

        public Builder setApkFileUrl(String apkFileUrl) {
            this.apkFileUrl = apkFileUrl;
            return this;

        }

        public Builder setUpgradeLog(String upgradeLog) {
            this.upgradeLog = upgradeLog;
            return this;

        }

        public Builder setTitle(String title) {
            this.title = title;
            return this;

        }

        public Builder setTargetSize(String targetSize) {
            this.targetSize = targetSize;
            return this;

        }

        public Builder setConstraint(boolean constraint) {
            this.constraint = constraint;
            return this;

        }

        public Builder setApkFileMd5(String apkFileMd5) {
            this.apkFileMd5 = apkFileMd5;
            return this;

        }

        public Builder setTargetPath(String targetPath) {
            this.targetPath = targetPath;
            return this;

        }

        public Builder setHideDialog(boolean hideDialog) {
            this.hideDialog = hideDialog;
            return this;

        }

        public Builder setIgnorable(boolean ignorable) {
            this.ignorable = ignorable;
            return this;

        }

        public Builder setDismissProgress(boolean dismissProgress) {
            this.dismissProgress = dismissProgress;
            return this;

        }

        public Builder setOnlyWifi(boolean onlyWifi) {
            this.onlyWifi = onlyWifi;
            return this;

        }

        public Builder setUpgradeListener(IUpgradeListener upgradeListener) {
            this.upgradeListener = upgradeListener;
            return this;
        }

        public AppUpgrader build() {

            if (apkFileUrl == null || newVersion == null || upgradeLog == null) {
                throw new NullPointerException("必要参数不能为空");
            }

            if (TextUtils.isEmpty(title)) {
                title = String.format("是否升级到 %s 版本？", newVersion);
            }

            if (TextUtils.isEmpty(targetPath)) {
                //sd卡是否存在
                String path = "";
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) || !Environment.isExternalStorageRemovable()) {
                    try {
                        File externalCacheDir = activity.getExternalCacheDir();
                        if (externalCacheDir != null) {
                            path = externalCacheDir.getAbsolutePath();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (TextUtils.isEmpty(path)) {
                        path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
                    }
                } else {
                    path = activity.getCacheDir().getAbsolutePath();
                }
                setTargetPath(path);
            }


            return new AppUpgrader(this);
        }

    }

}

